var PGInput; 
var currentVersion = "264"

$(document).ready(function() {

	if (amEditing){
		UpdateAndLoadFCKEditors();
	
	
		$('.formEditorBtnText').each(function(){
			if ($(this).attr('name') == "Save")
				{
				$(this).click(function(){ 
						UpdateAndUnloadFCKEditors();
						//SaveContentItem();
					});
				}
		});
	}
});

function UpdateAndLoadFCKEditors()
{
	//if (confirm("Loading FCK"))
	//{
	$(".formTextboxText").each(function(){
		$(this).val(revertURLs($(this).val()));  //this is to remove the old pt tags in the form
		
		var oFCKeditor = new FCKeditor( $(this).attr('name') );
		  if (oFCKeditor) {
			oFCKeditor.ToolbarSet = "Custom2";
			oFCKeditor.Height="250";
			 oFCKeditor.BasePath = '/imageserver/plumtree/common/custom/RichTextEditors/FCKEditor_v264/' ;
			 $(this).val(xreplace($(this).val(),'pt://images/plumtree/common/custom/FCKImages/','/imageserver/plumtree/common/custom/FCKImages/'));
			 oFCKeditor.ReplaceTextarea() ;
		  }
	  });
	 // }
}


function UpdateAndUnloadFCKEditors()
{	
	disp_alert("unloding...");
	$(".formTextboxText").each(function(){
	try{
		disp_alert("in the new sunloading fucntion for "+$(this).attr('name'));
		if (typeof(FCKeditorAPI) !== 'undefined'){
		var oFCKeditor = FCKeditorAPI.GetInstance($(this).attr('name') );
		//alert("gotinstance");
		oFCKeditor.UpdateLinkedField();
		//alert("updatedlinkedfield");
		$(this).show();
		
		//$('#'+$(this).attr('name')+'___Frame').remove();
		var fieldId = $(this).attr('name');
		//better way to remove FCK to get around other issues
		   var configElement = document.getElementById(fieldId+'___Config');
		   var frameElement = document.getElementById(fieldId+'___Frame');
		   var textarea = $(this).get(0);
		   //var editor = FCKeditorAPI.GetInstance(fieldId);
		   
		   if (oFCKeditor!=null && configElement && frameElement && configElement.parentNode==textarea.parentNode && frameElement.parentNode==textarea.parentNode && document.removeChild)
		   {
			 // editor.UpdateLinkedField();
			  configElement.parentNode.removeChild(configElement);
			  frameElement.parentNode.removeChild(frameElement);
			//  textarea.style.display = '';
			  delete FCKeditorAPI.__Instances[fieldId];
			  delete oFCKeditor;
		   }
		
		
		disp_alert("fckeditor REALLY removed");
		//alert($('#'+$(this).attr('name')+'___Frame'));
		var temp = $(this).val();
		//alert("about to call xreplace");
		$(this).val(xreplace(temp,'/imageserver/plumtree/common/custom/FCKImages/','pt://images/plumtree/common/custom/FCKImages/'));
		disp_alert("the value is"+$(this).val());
		}
		else
		disp_alert("fckeditor wasn't loaded");
		}
		catch(err){disp_err("Error unloading fckeditor"+ err.description);}
	});
}


function FCKeditor_OnComplete( editorInstance )
{
if (editorInstance.IsDirty())
	{
	//alert("was dirty after complete");
	//this is necessary because sometimes fckedior thinks the thing is dirty right away...
	editorInstance.ResetIsDirty();
	}
}

function CheckFCKChanged()
{
try{
if (amEditing){
var wasChagned = false;
//alert("in check fck changed");
	$(".formTextboxText").each(function(){
		var oFCKeditor = FCKeditorAPI.GetInstance($(this).attr('name') );
		if (oFCKeditor.IsDirty())
		{
			//(oFCKeditor.Name + "was dirty");
			wasChagned = true;
		}
		else
		{
			disp_alert(oFCKeditor.Name + "was not dirty");
		}
	});
	return wasChagned;
}
}
catch(err){return false;}
}

/*
 * Javascript URL Parser
 * @author jrharshath (http://jrharshath.wordpress.com/)
 * @description Parses any URL like string and returns an array or URL "Components"
 * 
 * Working demo located at http://jrharshath.qupis.com/urlparser/
 * While using in a webapp, use "urlparse(window.location.href)" to parse the current location of the web page
 * Free to use, just provide credits.
 */
function urlparse( str )
{
    var arr = str.split('#');

    var result = new Array();
    var ctr=0;
    for ( var part in arr )
    {
        var qindex = part.indexOf('?');
        result[ctr] = {};
        if( qindex==-1 )
        {
            result[ctr].mid=part;
            result[ctr].args = [];
            ctr++;
            continue;
        }
        result[ctr].mid = part.substring(0,qindex);
        var args = part.substring(qindex+1);
        args = args.split('&');
        var localctr = 0;
        result[ctr].args = new Array();
        for ( var val in args )
        {
            var keyval = val.split('=');
            result[ctr].args[localctr] = new Object();
            result[ctr].args[localctr].key = keyval[0];
            result[ctr].args[localctr].value = keyval[1];
            localctr++;
        }
        ctr++;
    }
    return result;
}






function disp_alert(text){
	try{
	console.log(text);
	}
	catch(err){
	//alert("Caught error"+err);
	}
}
function disp_err(text){
	try{
	console.error(text);
	}
	catch(err){
	//alert("Caught error"+err);
	}
}

function getTextArea(tag)
{	//This function traverses from the table of a content item editor down to the text area element.  The path has been hard coded and might need updated in the future
	return (((tag.childNodes[0]).childNodes[1]).childNodes[0]).childNodes[0];
}
	
function getObjInnerText(obj){
	if (obj.innerText) { // IE;
		return obj.innerHTML;
	}
	else if (obj.textContent)
		return obj.innerHTML;
	else return false;
	}
function getParent(obj){
	if (obj.parentElement) { // IE;
		return obj.parentElement;
	}
	else{
		if (obj.parentNode)
			{
			return obj.parentNode;
			}
	}
} 


function runOnClick(varname) 

{ 
      var spans = document.getElementsByTagName("SPAN"); 
	//disp_alert("in runOnClick for "+varname);
      for (i = 0; i < spans.length; i++) 

      { 	
            if (getObjInnerText(spans[i]) == varname) //The name  of your TextBox you want to edit.
			{     
                  tbl = getParent(spans[i]); 
                  while(tbl.tagName != 'TABLE') 
                  { 
                        tbl = getParent(tbl); 
                  } 
				textAreaTag=getTextArea(tbl);
				PGInput = textAreaTag; 
              //  PGInput.rows = 8; 
              //  PGInput.style.width = "100%" 
                PGInput.disabled = false; 
				break;
            } 
      } 
}

function runOnLoad(nameOfTextField) 

{ 
return null;
      var tds = document.getElementsByTagName("TD"); 

      for (i = 0; i < tds.length; i++) 

      { 

          //  if ((tds[i].innerHTML.indexOf("Checkin(false);") >= 0))
				if (getObjInnerText(tds[i]) != false)
					if (getObjInnerText(tds[i]).indexOf("Checkin(false);") >= 0)

            { 

               //   tds[i].innerHTML = tds[i].innerHTML.replace("Checkin(false);", "PGInput.disabled=false; Checkin(false); setTimeout('PGInput.disabled=true;',500000);");
		//disp_alert("<A href='#' onclick=\"OpenChild(\'"+nameOfTextField+"\')\">Click for rich text editor to edit the "+nameOfTextField+"</A>");
					//runOnClick(nameOfTextField);
                   document.write("<input type='button' value='Edit the "+nameOfTextField+"' onclick=\"OpenChild(\'"+nameOfTextField+"\')\"/>"); 

                  break; 

            } 

      }     

//      for (i = 0; i < tds.length; i++) 

      { 

//            if (tds[i].innerHTML.indexOf("SaveContentItem()") >= 0 & tds[i].innerHTML.indexOf("class=formEditorBtnText") >= 0)

            { 

  

             //     tds[i].innerHTML = tds[i].innerHTML.replace("SaveContentItem(); return false;", "PGInput.disabled=false; SaveContentItem(); PGInput.disabled=true; return false;");

             //     tds[i].innerHTML = tds[i].innerHTML.replace("CloseCIE(); return false;", "PGInput.disabled=false; CloseCIE(); setTimeout('PGInput.disabled=true;',500000); return false;");

             //     break; 

            } 

      }     

} 

function OpenChild(varname) 
{ 
        //var popArgs = new Array(PGInput.value); 
	//disp_alert("open child called with varname "+varname);

	runOnClick(varname);
	//var textAreas = document.getElementsByTagName("TEXTAREA");
	//disp_alert("there are " + textAreas.length + " TEXTAREAS");

      var child = window.open("/imageserver/plumtree/common/custom/RichTextEditors/FCKEditor_v"+currentVersion+"/_samples/basic.html","newWindow","height=350,width=700,resizable=yes");

} 


function xreplace(checkMe,toberep,repwith){
try{
var temp = checkMe;

var i = temp.indexOf(toberep);

while(i > -1)

{

temp = temp.replace(toberep, repwith);

i = temp.indexOf(toberep, i + repwith.length + 1);

}

return temp;
}
catch(err){
alert("error in xreplace: "+err);
}
}



function convertLinks(html) {

    var container = document.createElement("p");
    container.innerHTML = html;

    var anchors = container.getElementsByTagName("a");
    var list = [];

    for (var i = 0; i < anchors.length; i++) {
        var href = anchors[i].href;
		
		if (href.indexOf("portal/server.pt") >= 0)
			{
			disp_alert("foudn a portal link");
		
			var parsedURL = urlparse(href) 
			var usesCommonOpener = false;
			var open,objID,pageID,param,contenid;
			var i=0;
			for ( var key in parsedURL.args)
			{
				disp_alert("wtf");
				if (val.key === "open")
					{
						disp_alert("Uses common Opener");
						usesCommonOpener = true;
						open=val.value;
					}
				if (val.key === "objID")
					{ objID = val.value; }
				if (val.key === "PageID")
					{ pageID = val.value; }
									if (val.key === "param")
					{ param = val.value; }
									if (val.key === "contentid")
					{ contentid = val.value; }
			}
			if (usesCommonOpener)
			{
			       var text;
				   if (anchors[i].textContent === undefined)
						text = anchors[i].innerText;
				    else
						text = anchors[i].textContent;
				var tempnewhtml = "<pt:standard.openerlink xmlns:pt='http://www.plumtree.com/xmlschemas/ptui/ open=" + open + " objID = "+objID + "mode=2>"+text+"</pt:standard.openerlink>"		
			
				 var el = document.createElement('div');
                 el.innerHTML = tempnewhtml;
                 var range = document.createRange();
                 range.selectNodeContents(el);
                 var documentFragment = range.extractContents();
                 anchors[i].parentNode.insertBefore(documentFragment, anchors[i]);
                 anchors[i].parentNode.removeChild(anchors[i]);
				 disp_alert("replaced wtih "+tempnewhtml);
			}

		
		
			}

        //list.push(['<a href="' + href + '">' + text + '</a>', href, text]);
    }

    return container.innerHTML;
}



function convertURLs(input){
openString = "open";
objectIDString = "objID";
pageIDString = "PageID";
contentIDString = "contentid";
var temp = input;
myRegex=/\<a(\s*?.*?)?href\=\"https?:\/\/(\S*?)\.house\.gov\/portal\/server\.pt\?(open\=.*?)"(\s*?.*?)?\>(.*?)\<\/a\>/;
disp_alert("using regex:" + myRegex);
while ((myArray = myRegex.exec(temp)) != null)
	{
	disp_alert("found match:"+myArray);
	disp_alert("myarray3:"+myArray[3]);
	newString = "<pt:standard.openerlink ";
	if ((queryString(myArray[3],pageIDString) != undefined) && (queryString(myArray[3],pageIDString) != ""))
		newString = newString + "pt:objectid='"+queryString(myArray[3],pageIDString)+"' pt:classid='514'";
	else
		newString = newString + "pt:objectid='"+queryString(myArray[3],objectIDString)+"' pt:classid='"+queryString(myArray[3],openString)+"'";
	if ((queryString(myArray[3],contentIDString) != undefined) && (queryString(myArray[3],contentIDString) != ""))
		newString = newString + " pt:param='contentid' pt:value='"+queryString(myArray[3],contentIDString)+"'";
	newString = newString + " pt:mode='2' ";
	if ((myArray[1] != undefined) && (myArray[1] != ""))
		newString = newString + myArray[1];
	if ((myArray[4] != undefined) && (myArray[4] != ""))
		newString = newString + myArray[4];
	newString = newString +">"+myArray[5]+"</pt:standard.openerlink>";
	
	temp=temp.replace(myRegex,newString);
	}
return temp;
}



function convertURLsV2(input){
openString = "open";
objectIDString = "objID";
pageIDString = "PageID";
contentIDString = "contentid";
var temp = input;
myRegex=/\<a(\s*?.*?)?href\=\"https?:\/\/(\S*?)\.house\.gov\/portal\/server\.pt\?(open\=.*?)"(\s*?.*?)?\>(.*?)\<\/a\>/;
//myRegex = /\<a.*?href=[""'](?<url>.*?)[""'].*?>(?<name>.*?)</a>/;

disp_alert("using regex:" + myRegex);
while ((myArray = myRegex.exec(temp)) != null)
	{
	disp_alert("found match:"+myArray);
	disp_alert("myarray3:"+myArray[3]);
	newString = "<pt:standard.openerlink ";
	if ((queryString(myArray[3],pageIDString) != undefined) && (queryString(myArray[3],pageIDString) != ""))
		newString = newString + "pt:objectid='"+queryString(myArray[3],pageIDString)+"' pt:classid='514'";
	else
		newString = newString + "pt:objectid='"+queryString(myArray[3],objectIDString)+"' pt:classid='"+queryString(myArray[3],openString)+"'";
	if ((queryString(myArray[3],contentIDString) != undefined) && (queryString(myArray[3],contentIDString) != ""))
		newString = newString + " pt:param='contentid' pt:value='"+queryString(myArray[3],contentIDString)+"'";
	newString = newString + " pt:mode='2' ";
	if ((myArray[1] != undefined) && (myArray[1] != ""))
		newString = newString + myArray[1];
	if ((myArray[4] != undefined) && (myArray[4] != ""))
		newString = newString + myArray[4];
	newString = newString +">"+myArray[5]+"</pt:standard.openerlink>";
	
	temp=temp.replace(myRegex,newString);
	}
return temp;
}




function revertURLs(input){

	var temp = input;
	myRegex=/\<pt\:standard\.openerlink\s+pt\:objectid\=\'(\d+)\'\s*pt\:classid\=\'(\d+)\'\s*(?:pt\:param\=\'contentid\'\s*pt\:value\=\'(.*?)\')?\s*pt\:mode\=\'2\'(\s*?.*?)?\>(.*?)\<\/pt\:standard\.openerlink\>/;
	while ((myArray = myRegex.exec(temp)) != null)
		{
		disp_alert(myArray[3]);
		if ((myArray[3] == undefined) || (myArray[3] == ""))
			temp=temp.replace(myRegex,"<a href='https://"+location.host+"/portal/server.pt?open=$2&objID=$1&mode=2' $4>$5</a>")
		else
			temp=temp.replace(myRegex,"<a href='https://"+location.host+"/portal/server.pt?open=$2&objID=$1&mode=2&contentid=$3' $4>$5</a>")
		}
	return temp;
}


function getVersion()
	{
	return currentVersion;
	}
	


//these functions replace the image location of uploaded housenet images with their 
//dynamic pt tag equivalents
function getval() 
{ 
//disp_alert("getval");
//disp_alert(xreplace(PGInput.value,'pt://images/plumtree/common/custom/FCKImages/','/imageserver/plumtree/common/custom/FCKImages/'));
tempvar2=revertURLs(PGInput.value);
return xreplace(tempvar2,'pt://images/plumtree/common/custom/FCKImages/','/imageserver/plumtree/common/custom/FCKImages/');
} 

function setval(sval) 
{
//disp_alert("setval"); 
//tempvar=convertURLs(sval);
tempvar=convertLinks(sval);
PGInput.value = xreplace(tempvar,'/imageserver/plumtree/common/custom/FCKImages/','pt://images/plumtree/common/custom/FCKImages/');
} 


function queryString(theString,variable) {
//disp_alert("in querystring: theString is "+theString+" and variable is "+variable);
var query = theString;
query = xreplace(query,"&amp;&amp;","&amp;");
query = xreplace(query,"&amp;","&");
//disp_alert("afte the replaces, query is "+query);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
//disp_alert("checking "+pair[0]);
if (pair[0] == variable) {
return pair[1];
}
}
//disp_alert('Query Variable ' + variable + ' not found');
} 






